<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\AdapterWebController;
use App\Models\Agent\Agent;
use App\Models\User\UserClient;
use App\Models\User\UsersInfo;
use App\Modules\Auth\Auth;
use App\Modules\Department\Department;
use App\Modules\Role\Role;
use App\Modules\User\User;
use Illuminate\Http\Request;
//use Illuminate\Pagination\LengthAwarePaginator;
//use Illuminate\Support\Collection;


class UserController extends AdapterWebController
{

    /**
     * api 用户初次登录 获取token
     */
    public function addClientUser(Request $request)
    {
        $postData = array_filter($request->all());
        $uploadRes = $this->fileUpload($request, 'agreement');
        if (!$uploadRes['status']) {
            throw_exception('请上传协议备案');
        }
        $postData['agreement'] = $uploadRes['url'];
        $this->appLayerExec(User::class, 'addClientUser', $postData);
        return view('admin.jump')->with([
            'message'=>'提交成功！',
            'url' =>url('/admin/userClient'),
            'jumpTime'=>2,
        ]);
    }

    public function userClientDetail($id)
    {
        $postData['id'] = $id;
        $user = $this->appLayerExec(User::class, 'userClientDetail', $postData);
        return $user['res'];
    }

    //领取任务
    public function userGetTask(){
        $user = $this->appLayerExec(User::class, 'userGetTask');
        return  $user['res'];
    }

    //用户审核统计
    public function userCheck(){
        $count = $this->appLayerExec(User::class, 'userCheck');
        return view('admin/user/user',['counts'=>$count['res']]);
    }

    //筛选用户
    public function userClientList($status){
        $postData['phone_status'] = $status;
        $user = $this->appLayerExec(User::class, 'userClientList', $postData);
        return $user['res'];
    }

    //审核用户
    public function checkClientUser(Request $request,$id){
        if($request->isMethod('get')){
            return view('admin.user.check_client_user',['id'=>$id]);
        }
        $postData = array_filter($request->all());
        $res = $this->appLayerExec(User::class, 'checkClientUser', $postData);
        flash('审核成功')->success();
        return redirect()->back();
    }

    //更改phone_status
    public function updatePhoneStatus($id,$status){
        $postData['id'] = $id;
        $postData['phone_status'] = $status;
        $res = $this->appLayerExec(User::class, 'checkClientUser', $postData);
        return $res;
    }

    //用户联系时间
    public function userPhoneTime(){
        $count = $this->appLayerExec(User::class, 'userPhoneTime');
        return view('admin.user.user_phone_time',['counts'=>json_encode($count['res'])]);
    }

    //用户列表
    public function userList(Request $request){
        $check_man = UsersInfo::where('status','=',2)->select('check_man')->distinct()->get();
        $come_from = UsersInfo::where('status','=',2)->select('come_from')->distinct()->get();
        if(!empty($check_man)){$check_man->toArray();}
        if(!empty($come_from)){$come_from->toArray();}
        if(!$request->all()){
            $users = $this->appLayerExec(User::class, 'userList');
            return view('admin.user.user_list',['list'=>$users['res'],'user'=>1,'userListStatus'=>1,'client'=>1,'come_from'=>$come_from,'check_man'=>$check_man]);
        }
        $postData = array_filter($request->all());
        $users = $this->appLayerExec(User::class, 'userList', $postData);
        return view('admin.user.user_list',['list'=>$users['res'],'user'=>1,'userListStatus'=>1,'client'=>1,'come_from'=>$come_from,'check_man'=>$check_man]);
    }

    // 用户信息
    public function userInfo(Request $request)
    {
        if ($request->isMethod('get')) {
            $data['id'] = $request['id'];
            $user = $this->appLayerExec(User::class, 'userClientDetail', $data);
            return view('admin.user.user_info', ['user' => $user['res'][0]]);

        }
        return view('admin.user.user_info');
    }

    // 编辑用户信息
    public function userEditDetail(Request $request)
    {
        if ($request->isMethod('get')) {
            $data['id'] = $request['id'];
            $user = $this->appLayerExec(User::class, 'userClientDetail', $data);
            return view('admin.user.user_edit_info', ['user' => $user['res'][0]]);
        }
        $this->appLayerExec(User::class, 'userEditDetail', $request->all());
        flash('修改成功')->success();
        return redirect()->back();
    }

    // 终止协议
    public function terminationAgreement(Request $request)
    {
        $data['id'] = $request['id'];
        $data['status'] = 5;
        $rst = $this->appLayerExec(User::class, 'userEditDetail', $data);
        return $rst;
    }

    // 权限列表
    public function authList()
    {
        $res = $this->appLayerExec(Auth::class, 'list');
        $list = $res['res'];
        return view('admin.user.auth_list',['list'=>$list,'authListStatus'=>'1','user'=>'1','auth'=>'1']);
    }

    // 添加权限
//    public function addAuth(Request $request)
//    {
//        if($request->isMethod('get')){
//            return view('admin.user.add_auth',['user'=>'active']);
//        }
//        $res = $this->appLayerExec(Auth::class, 'list');
//        $list = $res['res'];
//       return view('admin.user.auth_list',['list'=>$list,'authListStatus'=>'1','user'=>'active']);
//    }

    // 角色列表
    public function roleList()
    {
        $res = $this->appLayerExec(Role::class, 'list');
        $list = $res['res'];
        return view('admin.user.role_list', ['list' => $list, 'roleListStatus' => '1', 'user' => '1', 'auth' => '1']);
    }

    // 添加角色
    public function addRole(Request $request)
    {
        $_where[] = ['status','=',1];
        $list = \App\Models\User\Department::select('id','name_cn')->where($_where)->get();
        if(!empty($list)){
            $list = $list->toArray();
        }
        if($request->isMethod('get')){
            return view('admin.user.add_role',['list'=>$list,'user'=>'active','auth'=>'1']);
        }
        $postData = $request->all();
        $res = $this->appLayerExec(Role::class, 'add', $postData);
        if($res['code'] == 200){
            flash('添加成功')->overlay();
        }
        return view('admin.user.add_role',['list'=>$list,'user'=>'1','auth'=>'1']);
    }

    // 编辑角色
    public function editRole(Request $request,$id)
    {
        $postData['id'] = $id;
        if($request->isMethod('get')){
            $res = $this->appLayerExec(Role::class, 'getRoleInfo', $postData);
            return view('admin.user.edit_role',['name'=>$res['res']['name_cn'],'id'=>$id,'user'=>'1','auth'=>'1']);
        }
        $postData = $request->all();
        $res = $this->appLayerExec(Role::class, 'edit', $postData);
        if($res['code'] == 200){
            flash('修改成功')->overlay();
        }
        return redirect('admin/roleList');
    }

    // 开启角色
    public function startRole($id)
    {
        $postData['id'] = $id;
        $res = $this->appLayerExec(Role::class, 'start', $postData);
        return redirect('admin/roleList');
    }

    // 禁用角色
    public function stopRole($id)
    {
        $postData['id'] = $id;
        $res = $this->appLayerExec(Role::class, 'stop', $postData);
        return redirect('admin/roleList');
    }

    //角色对应权限
    public function roleByAuth($id){
        $postData['auth_id'] = $id;
        $res = $this->appLayerExec(Auth::class, 'roleByAuth',$postData);
       // $searchResults = $res['res'];
//        $currentPage = LengthAwarePaginator::resolveCurrentPage()-1;
//        $collection = new Collection($searchResults);
//        $perPage = 10;
//        $currentPageSearchResults = $collection->slice($currentPage * $perPage, $perPage)->all();
//        $paginatedSearchResults= new LengthAwarePaginator($currentPageSearchResults, count($collection), $perPage);
//        $paginatedSearchResults->setPath('http://sanka.local:9080/admin/roleByAuth/594');
        //dd($paginatedSearchResults);
        return view('admin.user.role_by_auth',['list'=>$res['res'],'user'=>'1','auth_id'=>$id]);
    }

    //给某个角色一个权限(关系表)
    public function addAuthByRole($role_id,$auth_id){
        $postData['role_id'] = $role_id;
        $postData['auth_id'] = $auth_id;
        $res = $this->appLayerExec(Auth::class, 'addAuthByRole',$postData);
        return redirect('admin/roleByAuth/'.$auth_id);
    }

    //删除某个角色一个权限(关系表)
    public function removeAuthsByRole($role_id,$auth_id){
        $postData['role_id'] = $role_id;
        $postData['auth_id'] = $auth_id;
        $res = $this->appLayerExec(Auth::class, 'removeAuthsByRole',$postData);
        return redirect('admin/roleByAuth/'.$auth_id);
    }

    // 添加员工
    public function addManager(Request $request)
    {
        if($request->isMethod('get')){
            $_where[] = ['status','=',1];
            $list = \App\Models\User\Department::select('id','name_cn')->where($_where)->get();
            if(!empty($list)){
                $list = $list->toArray();
            }
            return view('admin.user.add_manager',['list'=>$list,'user'=>1,'addManagerStatus'=>1,'manager'=>1]);
        }
        $postData = $request->all();

        $users = $this->appLayerExec(User::class, 'addManager', $postData);
        flash('添加成功')->overlay();
        return redirect('admin/addManager');
    }
    // 根据部门找对应角色
    public function findRole(Request $request)
    {
        $postData = $request->all();
        $where['department_id'] = $postData['department_id'];
        $role = \App\Models\User\Role::select('id','name_cn')->where($where)->get();
        if(!empty($role)){
            $role = $role->toArray();
        }
        return json_encode($role);

    }
    // 员工列表
    public function list()
    {
        $users = $this->appLayerExec(User::class, 'list');
        return view('admin.user.list',['list'=>$users['res'],'user'=>1,'listStatus'=>1,'manager'=>1]);
    }

 /*   // 员工详情
    public function adminInfo($id)
    {
        $postData['id'] = $id;
        $res = $this->appLayerExec(User::class, 'info', $postData);
        $adminInfo = $res['res'];
        return view('admin/user/admin_info',['adminInfo'=>$adminInfo,'adminInfoStatus'=>'1','user'=>'1','manager'=>1]);
    }*/


    //编辑个人资料
    public function adminInfo(Request $request,$id){
        if($request->isMethod('get')){
            $postData['id'] = $id;
            $res = $this->appLayerExec(User::class, 'info', $postData);
            $adminInfo = $res['res'];
            //$role = \App\Models\User\Role::select('id','name')->get()->toArray();
        return view('admin/user/admin_info',['adminInfo'=>$adminInfo,'adminInfoStatus'=>'1','user'=>'1','manager'=>1]);
        }
        $postData = $request->all();
        unset($postData['_token']);
        \App\Models\User\User::where('id','=',$postData['id'])->update($postData);
        flash('修改成功')->overlay();
        return redirect()->back();
    }

    /**
     * 修改密码
     * @param Request $request
     */
    public function changePass(Request $request)
    {
        if ($request->isMethod('get')) {
            return view('admin.user.change_pass');
        }
        $postData = $request->except('_token');
        $res = $this->appLayerExec(User::class,'editSelfLoginPassword',$postData);
        if ($res['status'] == SUCCESS_STATUS) {
            return view('admin.default_admin_jump')->with(['jump_data' => ['status' => 1, 'msg' => '密码修改成功', 'goto' => url('/admin/adminlogin')]]);
        } else {
            flash('修改密码失败')->error();
            return redirect()->back();
        }
    }

    //员工离职
    public function changeManagerStatus($id=0){
        if($id == 0) {
            return view('admin.user.change_manager_status');
        }else{
            \App\Models\User\User::where('id','=',$id)->update(['status'=>0]);
        }
    }

    //编辑员工
    public function editManager(Request $request,$id){
        if($request->isMethod('get')){
            $postData['id'] = $id;
            $res = $this->appLayerExec(User::class, 'info', $postData);
            $adminInfo = $res['res'];
            $role = \App\Models\User\Role::select('id','name')->get();
            if(!empty($role)){
                $role = $role->toArray();
            }
            $depData = (new \App\Models\User\Department())->get();
            if(!empty($depData)){
                $depData = $depData->toArray();
            }
            return view('admin.user.edit_manager',['info'=>$adminInfo,'role'=>$role,'user'=>1,'manager'=>1, 'depData' => $depData]);
        }
        $postData = $request->all();
        unset($postData['_token']);
        \App\Models\User\User::where('id','=',$postData['id'])->update($postData);
        flash('修改成功')->success();
        return redirect()->back();
    }

    //用户开户
    public function userClient(){
        $count = $this->appLayerExec(User::class, 'userCheck');
        session(['monthPass'=>$count['res'][0]]);
        session(['monthRefuse'=>$count['res'][1]]);
        session(['todayPass'=>$count['res'][2]]);
        session(['todayRefuse'=>$count['res'][3]]);
        session(['monthPrecent'=>$count['res'][4]]);
        session(['todayPrecent'=>$count['res'][5]]);
        session(['currentCheck'=>$count['res'][6]]);
        session(['todayPassAll'=>$count['res'][7]]);
        session(['myCheck'=>$count['res'][8]]);
        $agent = Agent::select('simple_name','software_id')->distinct('simple_name','software_id')->where('status','=',2)->get();
        if(!empty($agent)){
            $agent = $agent->toArray();
        }
        return view('admin.user.user_client',['count'=>$count['res'],'user'=>1,'client'=>1,'userClientStatus'=>1,'agent'=>$agent]);
    }

    //更改用户头像
    public function updateUserImage(Request $request){
        $data = $request->all();
        $id = \App\Models\User\User::where('id','=',$data['id'])->update(['head_portrait'=>$data['url']]);
        return $id;
    }

    //电话接通
    public function dialout(Request $request)
    {
        $reqData = $request->all();
        if (!$reqData['Exten']) {
            return ['status' => 0, 'msg' => '请传递用户电话号码'];
        }
        $url = 'http://apis.7moor.com/v20160818/call/dialout/N00000035358?sig='.strtoupper(md5('N00000035358'.'357c32e0-d5bc-11e8-b80f-9b6791ff9165'.date('YmdHis', time())));
        $header = [
            'Accept:application/json',
            'Content-Type:application/json;charset=utf8',
            'Authorization:'.base64_encode('N00000035358'.':'.date('YmdHis', time())),
        ];

        $seats = $this->getSeats();
        $data = [
            'FromExten' => $seats,
            'Exten' => $reqData['Exten'],
            'ExtenType' => 'Local'
        ];
        $data = json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $response = curl_exec($ch);
        if($error=curl_error($ch)){
            die($error);
        }
        curl_close($ch);
        return $response;
    }

    //获取坐席号
    public function getSeats()
    {
        $postData['id'] = session('userId');
        $res = $this->appLayerExec(User::class, 'info', $postData);
        return $res['res']['uuid'];
    }


    //计算secret
    public function createSecret(array $data)
    {
        ksort($data);
        $str = '';
        foreach ($data as $k => $v) {
            $str .= $k.'='.$v.'&';
        }

        $str = rtrim($str, '&');
        dd($str);
        $str = urlencode($str).'357c32e0-d5bc-11e8-b80f-9b6791ff9165';
        return md5($str);
    }

    // 部门列表
    public function departmentList()
    {
        $res = $this->appLayerExec(Department::class, 'list');
        $list = $res['res'];
        return view('admin.user.department_list', ['list' => $list, 'departmentListStatus' => '1', 'user' => '1', 'auth' => '1']);
    }
    // 添加部门
    public function addDepartment(Request $request)
    {
        if($request->isMethod('get')){
            return view('admin.user.add_department',['user'=>'active','auth'=>'1']);
        }
        $postData = $request->all();
        $res = $this->appLayerExec(Department::class, 'add', $postData);
        if($res['code'] == 200){
            flash('添加成功')->success();
        }
        return view('admin.user.add_department',['user'=>'1','auth'=>'1']);
    }

    // 编辑部门
    public function editDepartment(Request $request,$id)
    {
        $postData['id'] = $id;
        if($request->isMethod('get')){
            $res = $this->appLayerExec(Department::class, 'getDepartmentInfo', $postData);
            return view('admin.user.edit_department',['name'=>$res['res']['name_cn'],'id'=>$id,'user'=>'1','auth'=>'1']);
        }
        $postData = $request->all();
        $res = $this->appLayerExec(Department::class, 'edit', $postData);
        if($res['code'] == 200){
            flash('修改成功')->overlay();
        }
        return redirect('admin/departmentList');
    }

    // 开启部门
    public function enableDepartment($id)
    {
        $postData['id'] = $id;
        $res = $this->appLayerExec(Department::class, 'start', $postData);
        return redirect('admin/departmentList');
    }

    // 禁用部门
    public function disableDepartment($id)
    {
        $postData['id'] = $id;
        $res = $this->appLayerExec(Department::class, 'stop', $postData);
        return redirect('admin/departmentList');
    }

    //部门对应角色
    public function departmentByRole($id){
        $postData['role_id'] = $id;
        $res = $this->appLayerExec(Department::class, 'departmentByRole',$postData);
        return view('admin.user.department_by_role',['list'=>$res['res'],'user'=>'1','role_id'=>$id]);
    }

    //给某个部门一个角色(关系表)
    public function addRoleByDepartment($department_id,$role_id){
        $postData['role_id'] = $role_id;
        $postData['department_id'] = $department_id;
        $res = $this->appLayerExec(Department::class, 'addRoleByDepartment',$postData);
        return redirect('admin/departmentByRole/'.$role_id);
    }

    //删除某个部门一个角色(关系表)
    public function removeRoleByDepartment($department_id,$role_id){
        $postData['role_id'] = $role_id;
        $postData['department_id'] = $department_id;
        $res = $this->appLayerExec(Department::class, 'removeRoleByDepartment',$postData);
        return redirect('admin/departmentByRole/'.$role_id);
    }

    //恢复用户
    public function userRenew($id){
        $res = UsersInfo::where('id','=',$id)->update(['status'=>2]);
        if($res){
            return view('admin.jump')->with(['url'=>'http://'.$_SERVER['HTTP_HOST'].'/admin/userInfo/'.$id]);
        }else{
            return '恢复失败';
        }
    }

}